<!--  -->
<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-button type="primary" @click="showCategoryDialog">添加分类</el-button>
             <!-- 商品分类列表 -->
               <!-- <el-table
                :data="categorysList" border stripe
                style="width: 100%">
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column 
                    prop="cat_name"
                    label="分类名称"
                >
                </el-table-column>
                <el-table-column
                    prop="email"
                    label="是否有效"
                >
                </el-table-column>
                <el-table-column
                    label="排序"
                >
                </el-table-column>
                <el-table-column
                    label="操作"
                >
                    <template slot-scope="scope">
                       
                       <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
                      
                       <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
                    </template>
                </el-table-column>
               </el-table> -->
            <!-- 使用第三方库 vue-table-with-tree-grid 改造商品分类列表 -->
            <tree-table
                :data="categorysList"
                :columns="columns"
                :selection-type = "false"
                :expand-type = "false"
                show-index
                index-text = "#"
                border
            >
                <!-- 是否有效的模板 -->
                <template slot = "isOk" slot-scope="scope">
                    <i class="el-icon-error" v-if="scope.row.cat_deleted" style="font-size: 20px; color: red"></i>
                    <i class="el-icon-success" v-else style="font-size: 20px; color: green"></i>
                </template>
                <!-- 排序的模板 -->
                <template slot = "order" slot-scope="scope">
                    <el-tag v-if="scope.row.cat_level == 0" size="medium">一级</el-tag>
                    <el-tag v-else-if="scope.row.cat_level == 1" type="success" size="medium">二级</el-tag>
                    <el-tag type="warning" v-else size="medium">三级</el-tag>
                </template>
                <!-- 操作的模板 -->
                <template slot = "operate" slot-scope="scope">
                   <el-button type="primary" icon="el-icon-edit" size = "small">编辑</el-button>
                   <el-button type="danger" icon="el-icon-delete" size = "small">删除</el-button>
                </template>
            </tree-table>
                <!-- 添加分类的dialog -->
                    <el-dialog title="添加分类" :visible.sync="categoryDialog" @close = "close">
                    <el-form :model="form" :rules="rules" ref="categoryForm">
                        <el-form-item label="分类名称"  prop = "cat_name" label-width="120px">
                            <el-input v-model="form.cat_name" autocomplete="off" ></el-input>
                        </el-form-item>
                        <!-- 层联选择器 -->
                        <el-form-item label="父级分类" label-width="120px">
                            <!-- options指定数据源 -->
                            <el-cascader
                                size = "small"
                                clearable
                                change-on-select
                                expand-trigger="hover"
                                v-model="selectKeys"
                                :options="parentList"
                                :props="defaultParams"
                                @change = "parentCateChanged"
                                ></el-cascader>
                        </el-form-item>
                    </el-form>
                        <div slot="footer" class="dialog-footer">
                            <el-button @click="categoryDialog = false">取 消</el-button>
                            <el-button type="primary" @click="addCate">确 定</el-button>
                        </div>
                    </el-dialog>

            <!-- 分页 -->
             <div class="block">
                <el-pagination
                :page-sizes="[2, 5, 8, 10]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :page-size="pagesize"
                :current-page="pagenum"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
                </el-pagination>
            </div>
        </el-card>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
//import引入的组件需要注入到对象中才能使用
components: {},
data() {
//这里存放数据
return {
    type:3,
    pagenum:1,
    pagesize:5,
    categorysList:[],
    total:0,
    columns:[
        {
            label:"分类名称",
            prop:"cat_name"
        },
         {
            label:"是否有效",
            // 当前列为模板列
            type:"template",
            template:"isOk"
        },
         {
            label:"排序",
            type:"template",
            template:"order"
        },
        {
            label:"操作",
            type:"template",
            template:"operate"
        },

    ],
    categoryDialog:false,
    // 添加分类的表单
    form: {
        cat_name: "",
        cat_pid: 0,
        cat_level:0
    }, 
     rules:{
          cat_name: [
            { required: true, message: '请输入分类名称', trigger: 'blur' },
            { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
          ]
    },
    selectKeys:[],
    defaultParams:{
        label:'cat_name',
        value:'cat_id',
        children:'children'
    },
    parentList:[]
 };
},
//监听属性 类似于data概念
computed: {},
//监控data中的数据变化
watch: {},
//方法集合
methods: {
    // 获取商品分类的数据
    async getGoodsCategorys(){
        const {data} = await this.$http({
            url:"categories",
            params:{
                type:this.type,
                pagenum:this.pagenum,
                pagesize:this.pagesize
            }
        })
        this.categorysList = data.data.result;
        // console.log(this.categorysList);
         this.total = data.data.total;
    },
    handleSizeChange(val) {
        // console.log(`每页 ${val} 条`);
        this.pagesize = val;
        this.getGoodsCategorys();
      },

    handleCurrentChange(val) {
        // console.log(`当前页: ${val}`);
        this.pagenum = val;
        this.getGoodsCategorys();
    },
    close(){
        this.$refs.categoryForm.resetFields();
        this.selectKeys = [];
        this.form.cat_pid = 0;
        this.form.cat_level = 0;
    },
    // 添加分类的对话框
    showCategoryDialog(){
        this.categoryDialog = true;
        this.getParentList();
    },
    // 获取父级分类的列表数据
    async getParentList(){
        const {data} = await this.$http({
            url:"categories",
            params:{
                type:2
            }
        })

        this.parentList = data.data;
        // console.log(this.parentList);
    },
    // 选择项发生变化触发
    parentCateChanged(){
        // console.log(this.selectKeys);
        if (this.selectKeys.length>0) {
            // 代表选中的是父级分类
           this.form.cat_pid = this.selectKeys[this.selectKeys.length-1];
           this.form.cat_level = this.selectKeys.length;
            return
        }else{
           this.form.cat_pid = 0;
           this.form.cat_level = 0;
        }
    },
    addCate(){

        this.$refs.categoryForm.validate(async valid => {
            if (!valid) {
                return
            }
            const {data} = await this.$http.post("categories",this.form);

            if (data.meta.status !== 201) {
                return this.$message.error("添加分类失败!")
            }
            this.$message.success("添加分类成功!");
            this.getGoodsCategorys();
            this.categoryDialog = false;
        })
    }
},
//生命周期 - 创建完成（可以访问当前this实例）
created() {
    this.getGoodsCategorys();
},
//生命周期 - 挂载完成（可以访问DOM元素）
mounted() {

},
beforeCreate() {}, //生命周期 - 创建之前
beforeMount() {}, //生命周期 - 挂载之前
beforeUpdate() {}, //生命周期 - 更新之前
updated() {}, //生命周期 - 更新之后
beforeDestroy() {}, //生命周期 - 销毁之前
destroyed() {}, //生命周期 - 销毁完成
activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.el-card{
    margin-top: 15px;
}
.zk-table{
    margin-top: 15px;
    margin-bottom: 15px;
}
.el-cascader{
    width: 100%;
}
</style>